package com.chookss.home.search;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.R;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.search.fragment.SearchAddressbookFragment;
import com.chookss.home.search.fragment.SearchAllFragment;
import com.chookss.home.search.fragment.SearchBaseFragment;
import com.chookss.home.search.fragment.SearchDataFragment;
import com.chookss.home.search.fragment.SearchDiaryFragment;
import com.chookss.home.search.fragment.SearchGalleryFragment;
import com.chookss.home.search.fragment.SearchGonggaoFragment;
import com.chookss.home.search.fragment.SearchInterviewFragment;
import com.chookss.home.search.fragment.SearchLongVideoFragment;
import com.chookss.home.search.fragment.SearchNewsFragment;
import com.chookss.home.search.fragment.SearchPlanFragment;
import com.chookss.home.search.fragment.SearchSmallVideoFragment;
import com.chookss.home.search.fragment.SearchTestFragment;
import com.chookss.home.search.fragment.SearchTimuFragment;
import com.chookss.home.search.fragment.SearchTuwenFragment;
import com.chookss.tiku.view.FlowLayout;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PermissionSpUtils;
import com.chookss.tools.Utils;
import com.chookss.view.ColorFlipPagerTitleView;
import com.chookss.view.RecycleViewDivider;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import scut.carson_ho.searchview.EditText_Clear;

public class MySearchActivity extends BaseAct {


    @BindView(R.id.et_search)
    EditText_Clear etSearch;
    @BindView(R.id.search_cancle)
    TextView searchCancle;
    @BindView(R.id.indicator_view)
    MagicIndicator indicatorView;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    @BindView(R.id.tvSearchChoice)
    TextView tvSearchChoice;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.searchChoiceLl)
    LinearLayout searchChoiceLl;
    @BindView(R.id.lvSearchInit)
    RecyclerView lvSearchInit;
    @BindView(R.id.rlInit)
    RelativeLayout rlInit;
    @BindView(R.id.flowLayout)
    FlowLayout flowLayout;
    @BindView(R.id.llHistory)
    LinearLayout llHistory;
    @BindView(R.id.llEmpty)
    LinearLayout llEmpty;
    @BindView(R.id.tvEmpty)
    TextView tvEmpty;
    @BindView(R.id.ivEmpty)
    ImageView ivEmpty;
    private Context mContext;
    private List<String> titleList = new ArrayList<>();
    private MyAdapter pagerAdapter=null;
    private ArrayList<SearchBaseFragment> fragments = new ArrayList<>();
    private String key = "";
    private int searchType = 0;//类型选择下标 //搜内容 搜人员
    private int index = 0;//分类下标
    private String typeName = "";//分类名称
    private List<String> initList = new ArrayList<>();
    private List<String> lists = new ArrayList<>();
    private FlowAdapter adapter;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_search);
        ButterKnife.bind(this);
        mContext = this;
        initState();
    }

    @Override
    public void initData() {

        key = getIntent().getStringExtra("key");
        typeName = getIntent().getStringExtra("typeName");
        index = getIntent().getIntExtra("index", 0);
        titleList.add("全部");
        fragments.add(new SearchAllFragment());
        if (PermissionSpUtils.getBoolean(this,"13",false)) {
            titleList.add("题目");
            fragments.add(new SearchTimuFragment());
        }
        if (PermissionSpUtils.getBoolean(this,"14",false)) {
            titleList.add("小视频");
            fragments.add(new SearchSmallVideoFragment());
        }
        if (PermissionSpUtils.getBoolean(this,"14",false)) {
            titleList.add("视频");
            fragments.add(new SearchLongVideoFragment());
        }
        if (PermissionSpUtils.getBoolean(this,"04",false)) {
            titleList.add("学习计划");
            fragments.add(new SearchPlanFragment());
        }
        if(PermissionSpUtils.getBoolean(this,"03",false)){
            titleList.add("资料库");
            fragments.add(new SearchDataFragment());
        }
        if(PermissionSpUtils.getBoolean(this,"02",false)){
            titleList.add("日志");
            fragments.add(new SearchDiaryFragment());
        }
        titleList.add("新闻");
        fragments.add(new SearchNewsFragment());
        if(PermissionSpUtils.getBoolean(this,"01",false)){
            titleList.add("公告");
            fragments.add(new SearchGonggaoFragment());
        }
        if (PermissionSpUtils.getBoolean(this,"05",false)) {
            titleList.add("考试");
            fragments.add(new SearchTestFragment());
        }
        if(PermissionSpUtils.getBoolean(this,"07",false)){
            titleList.add("通讯录");
            fragments.add(new SearchAddressbookFragment());
        }
        if(PermissionSpUtils.getBoolean(this,"06",false)){
            titleList.add("面试");
            fragments.add(new SearchInterviewFragment());
        }
        if(PermissionSpUtils.getBoolean(this,"17",false)){
            titleList.add("图文");
            fragments.add(new SearchTuwenFragment());
        }
        if(PermissionSpUtils.getBoolean(this,"26",false)){
            titleList.add("图库");
            fragments.add(new SearchGalleryFragment());
        }
        for (int i = 0; i < titleList.size(); i++) {
            if (!Utils.isNull(typeName)) {
                if (titleList.get(i).equals(typeName)) {
                    index = i;
                }
            }
        }
        String text = new ShareUtils().getString(this,Utils.getCacheName(this,StaticClass.ALL_HISTORY), "");
        if (!Utils.isNull(text)) {
            List<String> stringList = JSONArray.parseArray(text, String.class);
            if (stringList != null) {
                lists.addAll(stringList);
            }
        }
        tvEmpty.setText("暂无搜索记录");
        ivEmpty.setBackgroundResource(R.drawable.icon_default_no_search);
        if (Utils.isNull(key)) {
            llHistory.setVisibility(View.VISIBLE);
            if (lists.size() > 0) {
                adapter = new FlowAdapter(this, lists);
                flowLayout.setAdapter(adapter);
                viewPager.setVisibility(View.GONE);
                flowLayout.setVisibility(View.VISIBLE);
                llEmpty.setVisibility(View.GONE);
            } else {
                flowLayout.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
            }
        } else {
            viewPager.setVisibility(View.VISIBLE);
            llHistory.setVisibility(View.GONE);
            etSearch.setText(key);
            searchCancle.setText("搜索");
            initFragment();
        }
        CommonNavigator commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setScrollPivotX(0.65f);
//        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return titleList == null ? 0 : titleList.size();
            }

            @Override
            public IPagerTitleView getTitleView(Context context, int title_index) {
                SimplePagerTitleView simplePagerTitleView = new ColorFlipPagerTitleView(context);
                simplePagerTitleView.setIncludeFontPadding(false);
                simplePagerTitleView.setText(titleList.get(title_index));
                simplePagerTitleView.setTextSize(16);

                simplePagerTitleView.setPadding(Utils.dip2px(mContext, 15), 0, Utils.dip2px(mContext, 15), 0);


                simplePagerTitleView.setNormalColor(Color.rgb(129, 129, 129));
                simplePagerTitleView.setSelectedColor(Color.rgb(225, 36, 22));
                simplePagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(pagerAdapter==null){
                            index=title_index;
                            typeName=titleList.get(title_index);
                            indicatorView.onPageSelected(title_index);
                            indicatorView.getNavigator().notifyDataSetChanged();
                        }else{
                            viewPager.setCurrentItem(title_index);
                            Utils.hideInputKeyboard(MySearchActivity.this,etSearch);
                        }

                    }
                });
                return simplePagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(UIUtil.dip2px(context, 2));
                indicator.setLineWidth(UIUtil.dip2px(context, 42));
                indicator.setRoundRadius(UIUtil.dip2px(context, 1));
                indicator.setStartInterpolator(new AccelerateInterpolator());
                indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                indicator.setColors(Color.rgb(225, 36, 22));
                return indicator;
            }
        });
        indicatorView.setNavigator(commonNavigator);
        KLog.i(index);
        indicatorView.onPageSelected(index);
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {   // 按下完成按钮，这里和上面imeOptions对应
                    if (!Utils.isNull(v.getText().toString())) {
                        add(v.getText().toString());
                        key = v.getText().toString();
                        toSearch();
                        return false;   //返回true，保留软键盘。false，隐藏软键盘
                    } else {
                        MyToast.show("请输入关键词");
                    }
                }
                return true;   //返回true，保留软键盘。false，隐藏软键盘
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(searchCancle==null){
                    return;
                }
                if (Utils.isNull(etSearch.getText().toString())) {
                    searchCancle.setText("取消");
                } else {
                    searchCancle.setText("搜索");
                }

            }
        });
        NavigationTools.setWaterMark(this, "17");
        initLvDiretory();
    }

    //初始化
    private void initFragment() {

        for (int i = 0; i < fragments.size(); i++) {
            fragments.get(i).setKey(key);
            fragments.get(i).setSearchType(searchType + "");
            if (!Utils.isNull(typeName)) {
                if (titleList.get(i).equals(typeName)) {
                    index = i;
                }
            }
        }
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                indicatorView.onPageScrolled(position, positionOffset, positionOffsetPixels);
            }

            @Override
            public void onPageSelected(int position) {
                indicatorView.onPageSelected(position);
                index = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                indicatorView.onPageScrollStateChanged(state);
            }
        });
        pagerAdapter = new MyAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(pagerAdapter);
        viewPager.setOffscreenPageLimit(fragments.size() - 1);
        viewPager.setCurrentItem(index);
    }


    private void initLvDiretory() {
        initList.add("全部");
        initList.add("搜内容");
        initList.add("搜人员");
        lvSearchInit.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        lvSearchInit.addItemDecoration(new RecycleViewDivider(
                this, LinearLayoutManager.HORIZONTAL, Utils.dip2px(this, 0.5f), getResources().getColor(R.color.line_gray)
        ));
        InitAdapter adapter = new InitAdapter(R.layout.item_search_init, mContext, initList);
        lvSearchInit.setAdapter(adapter);
        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {

                if (position == 0) {
                    tvSearchChoice.setText(initList.get(position));
                } else {
                    tvSearchChoice.setText(initList.get(position).substring(1, initList.get(position).length()));
                }
                for (int i = 0; i < fragments.size(); i++) {
                    fragments.get(i).setSearchType(position + "");
                }
                searchType = position;
                adapter.notifyDataSetChanged();
                rlInit.setVisibility(View.GONE);
                ivChoice.setBackgroundResource(R.drawable.sear_arrow_down);
            }
        });
        rlInit.setOnClickListener(v -> {
            rlInit.setVisibility(View.GONE);
            ivChoice.setBackgroundResource(R.drawable.sear_arrow_down);
        });
    }

    class InitAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;

        public InitAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String entity) {
            TextView init = helper.getView(R.id.init);
            init.setText(entity);
            if (searchType == helper.getItemPosition()) {
                init.setSelected(true);
            } else {
                init.setSelected(false);
            }
        }
    }

    class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter(@NonNull FragmentManager fm, List<SearchBaseFragment> fragments) {
            super(fm);
        }

        @NonNull
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }
    }

    //再次搜素
    private void toSearch() {
        if(etSearch==null){
            return;
        }
        if (etSearch != null) {
            Utils.hideInputKeyboard(this, etSearch);
        }
        if (viewPager.getVisibility() == View.GONE) {
            viewPager.setVisibility(View.VISIBLE);
            llHistory.setVisibility(View.GONE);
            initFragment();
        } else {
            for (int i = 0; i < fragments.size(); i++) {
                fragments.get(i).setKey(key);
                fragments.get(i).setSearchType(searchType + "");
                if (index == i) {
                    fragments.get(i).refreshData();
                }
            }
        }
    }

    class FlowAdapter extends FlowLayout.Adapter<FlowAdapter.FlowViewHolder> {

        private static final String TAG = "FlowAdapter";

        private Context mContext;
        private List<String> mContentList;

        public FlowAdapter(Context mContext, List<String> mContentList) {
            this.mContext = mContext;
            this.mContentList = mContentList;
        }

        @Override
        public FlowAdapter.FlowViewHolder onCreateViewHolder(ViewGroup parent) {
            View view = LayoutInflater.from(mContext).inflate(R.layout.item_search_list, parent, false);
//            // 给 View 设置 margin
            ViewGroup.MarginLayoutParams mlp = new ViewGroup.MarginLayoutParams(view.getLayoutParams());
            int margin = Utils.dip2px(mContext, 6);
            mlp.setMargins(margin, margin, margin, margin);
            view.setLayoutParams(mlp);

            return new FlowAdapter.FlowViewHolder(view);
        }

        @Override
        public void onBindViewHolder(FlowAdapter.FlowViewHolder holder, int position) {
            holder.tvTitle.setText(mContentList.get(position));
            holder.ivDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    remove(position);
                }
            });
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    key = mContentList.get(position);
                    etSearch.setText(key);
                    viewPager.setVisibility(View.VISIBLE);
                    llHistory.setVisibility(View.GONE);
                    initFragment();
                    if (etSearch != null) {
                        Utils.hideInputKeyboard(MySearchActivity.this, etSearch);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return mContentList.size();
        }

        class FlowViewHolder extends FlowLayout.ViewHolder {
            TextView tvTitle;
            ImageView ivDelete;

            public FlowViewHolder(View itemView) {
                super(itemView);
                tvTitle = itemView.findViewById(R.id.tvTitle);
                ivDelete = itemView.findViewById(R.id.ivDelete);
            }
        }
    }

    private void add(String data) {
        // 设置 Adapter
        if(flowLayout==null){
            return;
        }
        if (!lists.contains(data)) {
            lists.add(data);
            saveSearchHistory();
            // 设置 Adapter
            adapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(adapter);
        }
    }

    private void remove(int position) {
        // 设置 Adapter
        if(flowLayout==null){
            return;
        }
        lists.remove(position);
        saveSearchHistory();
        // 设置 Adapter
        if (lists.size() > 0) {
            flowLayout.setVisibility(View.VISIBLE);
            adapter = new FlowAdapter(this, lists);
            flowLayout.setAdapter(adapter);
        } else {
            flowLayout.setVisibility(View.GONE);
        }


    }


    private void saveSearchHistory() {
        if (lists.size() > 6) {
            lists.remove(0);
        }
        String text = JSON.toJSONString(lists);
        new ShareUtils().putString(this,Utils.getCacheName(this,StaticClass.ALL_HISTORY), text);
    }

    @OnClick({R.id.search_record_back, R.id.searchChoiceLl, R.id.search_cancle, R.id.llvDelele})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search_record_back:
                finish();
                break;
            case R.id.llvDelele:
                if(flowLayout==null){
                    return;
                }
                new ShareUtils().putString(this,Utils.getCacheName(this,StaticClass.ALL_HISTORY), "");
                lists.clear();
                flowLayout.setVisibility(View.GONE);
                llEmpty.setVisibility(View.VISIBLE);
                break;
            case R.id.searchChoiceLl:
                if(rlInit==null){
                    return;
                }
                if (rlInit.getVisibility() == View.GONE) {
                    rlInit.setVisibility(View.VISIBLE);
                    ivChoice.setBackgroundResource(R.drawable.sear_arrow_up);
                }
                break;
            case R.id.search_cancle:
                if(searchCancle==null){
                    return;
                }
                if (searchCancle.getText().toString().equals("取消")) {
                    finish();
                } else {
                    //搜索
                    key = etSearch.getText().toString();
                    Utils.hideInputKeyboard(MySearchActivity.this, etSearch);
                    toSearch();
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
        } else {
            String msg = messageEvent.getMessage();
            if (!Utils.isNull(msg)) {
                for (int i = 0; i < titleList.size(); i++) {
                    if (titleList.get(i).equals(msg)) {
                        viewPager.setCurrentItem(i);
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (etSearch != null) {
            Utils.hideInputKeyboard(this, etSearch);
        }
    }
}
